package org.jxkj.utils;

import org.apache.commons.io.IOUtils;

import javax.script.*;
import java.io.InputStream;
import java.util.Map;

/**
 * User: jiangfy
 * Date: 2020/8/5
 */
public class ScriptTool {
    ScriptEngine engine;

    /**
     * 通过脚本文件初始化
     *
     * @param is
     * @param ctx 上下文变量
     * @throws Exception
     */
    public ScriptTool(InputStream is, Map<String, Object> ctx) throws Exception {
        engine = new ScriptEngineManager().getEngineByName("nashorn");
        Bindings bind = engine.getContext().getBindings(ScriptContext.GLOBAL_SCOPE);
        bind.put("ctx", ctx);
        if (is != null) {
            String script = IOUtils.toString(is, "utf-8");
            engine.eval(script);
        }
    }

    /**
     * 通过脚本代码初始化
     *
     * @param script
     * @param ctx    上下文变量
     * @throws Exception
     */
    public ScriptTool(String script, Map<String, Object> ctx) throws Exception {
        engine = new ScriptEngineManager().getEngineByName("nashorn");
        Bindings bind = engine.getContext().getBindings(ScriptContext.GLOBAL_SCOPE);
        bind.put("ctx", ctx);
        engine.eval(script);
    }

    /**
     * 执行默认方法
     *
     * @param data
     * @return
     * @throws Exception
     */
    public Object execute(Object... data) throws Exception {
        return call("main", data);
    }

    /**
     * 调用指定方法
     *
     * @param func 调用的函数名
     * @param data
     * @return
     * @throws Exception
     */
    public Object call(String func, Object... data) throws Exception {
        Invocable invocable = (Invocable) engine;
        return invocable.invokeFunction(func, data);
    }

    public ScriptEngine getEngine() {
        return engine;
    }
}
